<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\facade\Session;

class Login extends Controller
{
	public function index()
	{
        if (Session::has('user')) {
            $this->redirect(url('admin/index/index'));
        }

        if ($this->request->isPost() && $this->request->isAjax()) {
            if(!captcha_check(trim($this->request->post('captcha/s', '')))) {
                $this->result('', 1, '验证码错误');
            }

            $account = trim($this->request->post('account/s', ''));
            $password = trim($this->request->post('password/s', ''));
            $user = Db::table('user')->where(['account' => $account, 'password' => md5($password)])->find();
            if (!$user) {
                $this->result('', 1, '账号或密码错误');
            }

            // 获取权限
            $role = Db::table('role')->where(['id' => $user['role_id']])->find();
            if (!$role) {
                $this->result('', 1, '用户角色异常');
            }

            $role['conts'] = array_merge(['index', 'editor'], explode(',', $role['conts']));

            Session::set('user', $user);
            Session::set('role', $role);

            // 登录信息更新
            Db::table('user')->where(['id' => $user['id']])->update([
                'login_time'    => date("Y-m-d H:i:s"), 
                'login_ip'      => $this->request->ip(),
            ]);

            // 登录日志写入
            Db::table('log')->insert([
                'name'          => $user['name'],
                'login_time'    => date("Y-m-d H:i:s"), 
                'login_ip'      => $this->request->ip(),
            ]);

            $this->result('', 0, '登录成功，正在跳转...');
        }

		return $this->fetch();
	}

    public function logout()
    {
        Session::clear();
    }
}
